//
//  Common.swift
//  HighScoreTalk
//
//  Created by apple on 16/1/30.
//  Copyright © 2016年 apple. All rights reserved.
//

import Foundation
import UIKit
import CoreData
class Style {
    
    //MARK:主题色
    static let themeColor1 = UIColor(red: 0x1a/255.0, green: 0xad/255.0, blue: 0x55/255.0, alpha: 1.0)
    static let themeColor2 = UIColor(red: 0x43/255.0, green: 0x8b/255.0, blue: 0xf6/255.0, alpha: 1.0)
    static let textColor1 = UIColor(red: 0x33/255.0, green: 0x33/255.0, blue: 0x33/255.0, alpha: 1.0)
    static let textColor2 = UIColor(red: 0x66/255.0, green: 0x66/255.0, blue: 0x66/255.0, alpha: 1.0)
    static let textColor3 = UIColor(red: 0x99/255.0, green: 0x99/255.0, blue: 0x99/255.0, alpha: 1.0)
}

func ScreenWidth()->CGFloat{
    return UIScreen.mainScreen().bounds.size.width
}
func ScreenHeight()->CGFloat{
    return UIScreen.mainScreen().bounds.size.height
}
// MARK:Commont
extension UIButton {
    //配制成空心样式
    func configureToEmptyStyle(title:String){
        backgroundColor = UIColor.clearColor()
        layer.cornerRadius = 4
        layer.masksToBounds = true
        layer.borderColor = UIColor.themeColor().CGColor
        layer.borderWidth = 0.5
        setTitle(title, forState: .Normal)
        titleLabel?.font = UIFont.systemFontOfSize(18)
        setTitleColor(UIColor.themeColor(), forState: .Normal)
    }
    func configureToEmptyStyle(){
        let title = self.titleForState(.Normal)
        configureToEmptyStyle(title!)
    }
    
    //配置成实心样式
    func configureToFullStyle(title:String){
        backgroundColor = UIColor.themeColor()
        layer.cornerRadius = 4
        layer.masksToBounds = true
        setTitle(title, forState: .Normal)
        titleLabel?.font = UIFont.systemFontOfSize(18)
        setTitleColor(UIColor.whiteColor(), forState: .Normal)
     }
}

// MARK:UIColor
extension UIColor {
    static func titleColor()->UIColor{
        return UIColor(red: 0x33/255.0, green: 0x33/255.0, blue: 0x33/255.0, alpha: 1.0)
    }
    static func hintColor()->UIColor{
        return UIColor(red: 0x99/255.0, green: 0x99/255.0, blue: 0x99/255.0, alpha: 1.0)
    }
    
    static func themeColor()->UIColor{
        return UIColor(red: 0x54/255.0, green: 0xa8/255.0, blue: 0xe3/255.0, alpha: 1.0)
    }
    static func themeRedColor()->UIColor{
        return UIColor(red: 0xf3/255.0, green: 0x98/255.0, blue: 0x00/255.0, alpha: 1.0)
    }
}
 

extension UIViewController {
    func addCommonStyleBackItem(target target:AnyObject,action:Selector) {
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_image"), style: .Plain, target: target, action: action)
    }
    
    /// 添加公共样式返回按钮
    func addCommonStyleBackItem() {
        addCommonStyleBackItem(target: self, action: #selector(UIViewController.commonStyleBack(_:)))
    }
    
    internal func commonStyleBack(item:AnyObject){
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    func addBackButton()->UIButton {
        let button = UIButton()
        button.setImage(UIImage(named: "icon_back"), forState: .Normal)
        view.addSubview(button)
        button.snp_makeConstraints { (make) in
            make.leading.equalTo(view).offset(14.5)
            make.top.equalTo(view).offset(15.5)
        }
        return button
    }
    
    
    //让导航栏透明
    func makeNavigationBarTransparent(){
        UINavigationBar.appearance().setBackgroundImage(UIImage(fromColor: UIColor.clearColor(), rect: CGRectMake(0, 0, 100, 100)), forBarPosition:.Any, barMetrics: .Default)
    }
    func makeNavigationBarNotTransparent(){
        UINavigationBar.appearance().setBackgroundImage(UIImage(fromColor: UIColor.whiteColor(), rect: CGRectMake(0, 0, 100, 100)), forBarPosition:.Any, barMetrics: .Default)
    }
    
    
    func addNavgationTitles(titles:[String],clickHandler:(NSInteger)->Void) {
        let titleView = UIScrollView(frame: CGRectMake(0,0,200,20))
        self.navigationItem.titleView = titleView
    }
    
 
}

extension UIView {
    func addSubviews(views:[UIView]) {
        views.forEach { (view) in
            addSubview(view)
        }
    }
    
    func addExitKeyBoardGestureRecognizer(){
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UIView.tap(_:))))
    }
    
    func tap(g:UITapGestureRecognizer) {
         endEditing(true)
    }
    
    func makeRound(a:CGFloat) {
        layer.cornerRadius = a
        layer.masksToBounds = true
    }
    
    func makeRound() {
        makeRound(CGRectGetWidth(bounds)/2.0)
    }
    
    
    //添加标签
    func addTags(tags:[String]) {
        var labels = [UILabel]()
        for  i in 0..<tags.count{
            let label = UILabel()
            label.textColor = UIColor.whiteColor()
            label.backgroundColor = Style.themeColor1
            label.text = tags[i]
            addSubview(label)
            label.sizeToFit()
            label.layer.cornerRadius = 2
            label.layer.masksToBounds = true
            labels.append(label)
            label.snp_makeConstraints(closure: { (make) in
                if i == 0 {
                    make.leading.equalTo(self.snp_leading)
                } else {
                    make.leading.equalTo(labels[i-1].snp_trailing).offset(10.5)
                }
                make.width.equalTo(label.frame.size.width+8)
                make.height.equalTo(self.snp_height)
                make.centerY.equalTo(self.snp_centerY)
            })
        }
    }
}

extension UITableView {
    func configureToCommonStyle()
    {
        self.separatorStyle = .None
        self.backgroundColor = UIColor(red: 248/255.0, green: 248/255.0, blue: 248/255.0, alpha: 1)
    }

}


extension NSManagedObject {
    static func insert(dictionary:Dictionary<String,AnyObject>)->NSManagedObject? {
        let className = NSStringFromClass(self.classForCoder())
        print(className)
        var instance:NSManagedObject?
        if let name = className.componentsSeparatedByString(".").last {
            instance = NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: DataController.shareInstance.managedObjectContext)
            for (k,v) in dictionary {
                if !v.isKindOfClass(NSNull.classForCoder()) {
                    instance?.setValue(v, forKey: k)
                }
            }
        }
        return instance
    }
    
    func delete() {
        DataController.shareInstance.managedObjectContext.deleteObject(self)
        DataController.shareInstance.saveContext()
    }
    
    func alter(block:(NSManagedObject)->Void) {
        block(self)
        do {
            try DataController.shareInstance.managedObjectContext.save()
        } catch let error as NSError {
            print("error:\(error)")
        }
    }
}


extension UITextField {
    func configureToCommonStyle(){
        borderStyle = .None
        layer.cornerRadius = CGRectGetHeight(self.bounds) / 2
        layer.masksToBounds = true
        background = UIImage(named: "auth_textfield_image")
        if placeholder?.characters.count > 0 {
            attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(14),NSForegroundColorAttributeName:UIColor(red: 0xff/255.0, green: 0xff/255.0, blue: 0xff/255.0, alpha: 1.0)])
        }
    }
    
    
    func addLeftView(imagename:String){
        let view = UIView(frame: CGRectMake(0,0,62,48))
        let button = UIButton()
        button.setImage(UIImage(named: imagename), forState: .Normal)
        button.sizeToFit()
        view.addSubview(button)
        button.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.trailing.equalTo(view).offset(-10)
        }
        leftView = view
        leftViewMode = .Always
    }
    
    func addSeePasswordButton(){
        let view = UIView(frame: CGRectMake(0,0,52,48))
        let button = UIButton()
        button.setImage(UIImage(named: "auth_password_icon"), forState: .Normal)
        button.sizeToFit()
        button.addTarget(self, action: #selector(UITextField.see), forControlEvents: .TouchUpInside)
        view.addSubview(button)
        button.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.trailing.equalTo(view).offset(0)
        }
        rightView = view
        rightViewMode = .Always
    }
    
 
    
    internal func see() {
        secureTextEntry = !secureTextEntry
    }
    
    
    func addPhoneLeftView() {
        let view = UIView(frame: CGRectMake(0,0,70,40))
        let imageView = UIImageView(image: UIImage(named:"img_phone"))
        view.addSubview(imageView)
        let label = UILabel()
        label.text = "+86"
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.titleColor()
        view.addSubview(imageView)
        view.addSubview(label)
        imageView.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.leading.equalTo(view).offset(10)
        }
        label.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.trailing.equalTo(view).offset(-6)
        }
        leftView = view
        leftViewMode = .Always
    }
    
    func addPasswordLeftView() {
        let view = UIView(frame: CGRectMake(0,0,37,40))
        let imageView = UIImageView(image: UIImage(named:"img_password"))
        view.addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.leading.equalTo(view).offset(10)
        }
 
        leftView = view
        leftViewMode = .Always
    }
    
    func addMessageLeftView() {
        let view = UIView(frame: CGRectMake(0,0,37,40))
        let imageView = UIImageView(image: UIImage(named:"img_message"))
        view.addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.leading.equalTo(view).offset(10)
        }
        
        leftView = view
        leftViewMode = .Always
    }
    
    func addEmptyLeftView() {
        let view = UIView(frame: CGRectMake(0,0,6,40))
        leftView = view
        leftViewMode = .Always
    }
}

extension Double {
    func floor()->Int {
        return Int(self)
    }
    func ceiling()->Int {
        if self - Double(floor()) > 0 {
            return floor()+1
        }
        return floor()
    }
    func floor(interval:Double)->Double {
       let integerPart = Double(Int(self))
       let fractionPart = self - integerPart
       let num = Int(fractionPart/interval)
       return integerPart+Double(num)*interval
    }
    
    func ceiling(interval:Double)->Double {
        let f = floor(interval)
        return (self-f > 0) ? f+interval : f
    }

}

extension UIView {
    class func showMaskView(handler:(UIView)->Void)
    {
        let contentView:UIView = UIView()
        contentView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        app.window!.addSubview(contentView)
        contentView.snp_makeConstraints {make in
            let superView:UIView = app.window!
            make.edges.equalTo(superView)
        }
        let g = UITapGestureRecognizer(target: self, action: #selector(UIView.maskViewTap(_:)))
        contentView.addGestureRecognizer(g)
        handler(contentView)
    }
    
    static func maskViewTap(g:UIGestureRecognizer)
    {
        g.view?.removeFromSuperview()
    }

}



